import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:search_people/entrance/route/router_config.dart';
import 'package:search_people/entrance/route/routes.dart';
import 'package:search_people/utils/httputils/http_man.dart';
import 'package:search_people/utils/methodchannelmanager.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:get/get.dart';
import 'bean/version_update_model.dart';
import 'utils/check_update.dart';
import 'utils/dialog_util.dart';
import 'utils/httputils/urlpath.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';
import 'utils/jpusher.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
      overlays: [SystemUiOverlay.bottom, SystemUiOverlay.top]);
  MethodChannelManager.initChannel();
  // JPushMan().initJpush();
  // WXUtil().register();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
  DateTime? lastTime;
  @override
  Widget build(BuildContext context) {
    final easyload = EasyLoading.init();

    // if (GetPlatform.isAndroid) {
    //   CheckUpdate().initXUpdate().then((value) {
    //     //初始化检测更新
    //     FlutterXUpdate.checkUpdate(
    //       url: UrlPath.checkUpdate,
    //       // themeColor: '#FF27AD63'
    //     );
    //   });
    // } else if (GetPlatform.isIOS) {
    //   _checkUpdate();
    // }

    return ScreenUtilInit(
      designSize: const Size(393, 844),
      splitScreenMode: false,
      minTextAdapt: false,
      builder: (context, child) => WillPopScope(
          child: RefreshConfiguration(
            hideFooterWhenNotFull: true, //列表数据不满一页,不触发加载更多
            child: GetMaterialApp(
              theme: ThemeData(
                // fontFamily: 'pingfangM'，    //设置全局字体
                primarySwatch: Colors.blue,
              ),
              initialRoute: RouterPath.splash,
              onGenerateRoute: MyRouterConfig.generateRoute,
              // navigatorObservers: [UmengAppAnalysis(), ],
              getPages: RouterPages.getPages,
              localizationsDelegates: [
                RefreshLocalizations.delegate,
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate, //iOS
                BrnLocalizationDelegate.delegate
              ],
              supportedLocales: const [
                Locale('zh', 'CN'),
                Locale('en', 'US'),
              ],
              builder: (context, child) {
                child = easyload(context, child);
                child = MediaQuery(
                    //设置文字大小不随系统设置改变
                    data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),

                    //全局设置键盘收缩
                    child: GestureDetector(
                      onTap: () {
                        FocusScopeNode focus = FocusScope.of(context);
                        if (!focus.hasPrimaryFocus &&
                            focus.focusedChild != null) {
                          FocusManager.instance.primaryFocus?.unfocus();
                        }
                      },
                      child: child,
                    ));
                return child;
              },
            ),
          ),
          onWillPop: () async {
            if (lastTime != null) {
              if (DateTime.now().difference(lastTime!) >
                  const Duration(seconds: 1)) {
                return true;
              }
            }
            lastTime = DateTime.now();
            EasyLoading.showToast('再次点击退出程序');
            return false;
          }),
    );
  }

  void _checkUpdate() async {
    var res = await HttpMan.instance.get(UrlPath.checkUpdate, loadding: false);
    var _data = jsonDecode(res.data);
    var md = VersionUpdateModel.fromJson(_data);
    if (md.code == 0) {
      PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
        var _currVersion = packageInfo.version;
        var res = md.versionName!.compareTo(_currVersion);
        if (res == 1) {
          showAlert(
            title: '更新提示',
            msg: md.modifyContent,
            sureAction: () {
              if (md.appleUrl != null) {
                launch(md.appleUrl!);
              }
            },
          );
        }
      });
    }
  }
}
